package cn.sciento.starter.social.sina.connection;

import com.google.common.base.Charsets;
import java.util.Map;
import cn.sciento.starter.social.core.common.connect.SocialTemplate;
import cn.sciento.starter.social.core.provider.Provider;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.social.oauth2.AccessGrant;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;

public class SinaTemplate extends SocialTemplate {
  public SinaTemplate(Provider provider) {
    super(provider);
    setUseParametersForClientAuthentication(true);
  }
  
  protected RestTemplate createRestTemplate() {
    RestTemplate restTemplate = super.createRestTemplate();
    restTemplate.getMessageConverters().add(new StringHttpMessageConverter(Charsets.UTF_8));
    return restTemplate;
  }
  
  protected AccessGrant postForAccessGrant(String accessTokenUrl, MultiValueMap<String, String> parameters) {
    Map result = (Map)getRestTemplate().postForObject(accessTokenUrl, parameters, Map.class);
    if (result == null)
      throw new RestClientException("access token endpoint returned empty result"); 
    String accessToken = (String)result.get("access_token");
    Long expiresIn = Long.valueOf(String.valueOf(result.get("expires_in")));
    String uid = (String)result.get("uid");
    return new SinaAccessGrant(accessToken, expiresIn, uid);
  }
}
